'use strict';

const db = uniCloud.database();
const collection = db.collection('food-banner');

exports.main = async (event, context) => {
  const { 
    page = 1, 
    pageSize = 10, 
    keyword = '', 
    status = '',
    linkType = '',
    sortField = 'sort',
    sortOrder = 'desc'
  } = event.data || {};
  
  // 确保页码和分页条数为有效数值
  const currentPage = Math.max(1, parseInt(page) || 1);
  const currentPageSize = Math.max(1, Math.min(100, parseInt(pageSize) || 10));
  
  try {
    // 构建查询条件
    let query = collection;
    
    // 关键词搜索（按标题搜索）
    if (keyword) {
      query = query.where({
        title: new RegExp(keyword, 'i')
      });
    }
    
    // 状态筛选
    if (status !== '') {
      query = query.where({
        status: parseInt(status)
      });
    }
    
    // 链接类型筛选
    if (linkType !== '') {
      query = query.where({
        link_type: parseInt(linkType)
      });
    }
    
    // 获取总数
    const countResult = await query.count();
    const total = countResult.total;
    
    // 分页查询
    const result = await query
      .orderBy(sortField, sortOrder)
      .orderBy('create_date', 'desc')
      .skip((currentPage - 1) * currentPageSize)
      .limit(currentPageSize)
      .get();
    
    return {
      code: 200,
      message: '查询成功',
      data: {
        list: result.data,
        total,
        page: currentPage,
        pageSize: currentPageSize,
        totalPages: Math.ceil(total / currentPageSize)
      }
    };
  } catch (error) {
    console.error('查询轮播图失败:', error);
    return {
      code: 500,
      message: '查询失败',
      data: null
    };
  }
};